#include "./linkedList.h"

LinkedListStruct* linkedList_new() {
  mempool_init(0x400);
  LinkedListStruct* self =
      (LinkedListStruct*)mempool_alloc(sizeof(LinkedListStruct));
  self->length = 0;
  self->first = NULL;
  self->last = NULL;
  self->current = self->first;
  return self;
}
void linkedList_del(LinkedListStruct* self) {
  self->current = self->first;
  while (self->current != NULL) {
    linkedList_delData(self, NULL);
    self->current = self->current->next;
  }
  mempool_free(self);
}

LinkedListUnitStruct* linkedList_addData(LinkedListStruct* self, void* data) {
  if (self->first == NULL) {
    self->first =
        (LinkedListUnitStruct*)mempool_alloc(sizeof(LinkedListUnitStruct));
    self->first->data = data;
    self->first->prior = NULL;
    self->first->next = NULL;
    self->last = self->first;
  } else {
    self->last->next =
        (LinkedListUnitStruct*)mempool_alloc(sizeof(LinkedListUnitStruct));
    self->last->next->data = data;
    self->last->next->prior = self->last;
    self->last->next->next = NULL;
    self->last = self->last->next;
  }
  self->length = self->length + 1;
  return self->last;
}

void linkedList_delData(LinkedListStruct* self, void* data) {
  if (data != NULL) {
    self->current = linkedList_findData(self, data);
  }  //如果为NULL则删除current
  if (self->current == NULL) {
    return;
  }
  if (self->current->prior) {
    self->current->prior->next = self->current->next;
  } else {
    self->first = self->current->next;
  }
  if (self->current->next) {
    self->current->next->prior = self->current->prior;
  } else {
    self->last = self->current->prior;
  }
  self->length = self->length - 1;
  mempool_free(self->current);
}

LinkedListUnitStruct* linkedList_findData(LinkedListStruct* self, void* data) {
  self->current = self->first;
  while (self->current != NULL) {
    if (self->current->data == data) {
      return self->current;
    }
    self->current = self->current->next;
  }
  return NULL;
}
